package cn._2dland.uploader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

import cn._2dland.uploader.utils.Logger;

public class TaskReader {
	private int lineNum;
	private BufferedReader reader = null;

	public TaskReader(String taskFile) {
		try {
			TextFileInputStream tis = new TextFileInputStream(new FileInputStream(taskFile));
			reader = new BufferedReader(new InputStreamReader(tis, tis.getCharset()));
			lineNum = 1;
		} catch (Exception e) {
			Logger.error(e);
		}
	}

	public UploadTask next() {
		if(reader == null)
			return null;

		UploadTask task = null;
		try {
			for(String line; (line=reader.readLine()) != null; lineNum ++){
				// 注释行或空白行，跳过
				if(canSkip(line)) continue;

				// 解析行
				task = parse(line);
				// 任务格式错误
				if(task == null) {
					Logger.writec("任务文件第 " + lineNum + " 行格式有误");
				} else {
					break;
				}
			}
		} catch (Exception e) {
			Logger.error(e);
		}

		return task;
	}

	// 是否需要跳过
	private boolean canSkip(String line) {
		return "".equals(line.trim()) || line.matches("^//.*$");
	}

	private UploadTask parse(String line) {
		UploadTask task = null;

		try {
			String tmp[] = line.split("\\|");
			if(tmp.length < 2)
				throw new Exception("任务定义不合法！");

			String type = tmp[0];
			if(!ClientFactory.isSupport(type))
				throw new Exception("不支持的任务类型！");

			// 校验通过，构造任务
			task = new UploadTask();
			task.type = type;
			task.file = new File(tmp[1]);
			task.fileName = task.file.getName();

			// 填充其他信息
			if(tmp.length >= 3)
				task.category = tmp[2];
			if(tmp.length >= 4)
				task.title = tmp[3];
			if(tmp.length >= 5)
				task.descript = tmp[4];
			if(tmp.length >= 6)
				task.tags = tmp[5];
			if(tmp.length >= 7)
				task.source = tmp[6];
			
		} catch (Exception e) {
			task = null;
		}

		return task;
	}

	public void close() {
		try {
			reader.close();
		} catch (Exception e) {}
	}
}

/**
 * 文本输入流类，进行了简单的编码检测
 * @author deadblue
 */
class TextFileInputStream extends FilterInputStream {
	private String charset = null;

	public TextFileInputStream(InputStream is) {
		super(is);

		try {
			// 在流开头进行标记
			super.mark(3);

			// 读取前三字节
			byte[] b = new byte[3];
			super.read(b);
			if(b[0] == -17 && b[1] == -69 && b[2] == -65) {
				charset = "utf-8";
			} else {
				charset = "gbk";
				super.reset();
			}
		} catch (Exception e) {}
	}
	
	public String getCharset() {
		return charset;
	}
}